'use strict'

const { Controller } = require('egg')
const captcha = require('svg-captcha')
const { sign } = require('jsonwebtoken')
class userController extends Controller {
  async login() {
    const { ctx, app } = this
    try {
      const { phoneNumber, veriCode } = this.ctx.body
      const userData = await app.mysql.get('users', { phone: phoneNumber })
      if (userData?.user_id) {
        this.ctx.body = {
          code: 0,
          msg: '登陆成功',
        }
      } else {
        this.ctx.body = {
          code: -1,
          msg: '手机号错误，请重试',
        }
      }
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: error.message,
      }
    }
  }

  // 获取用户信息: users/getUserInfo

  async getUserInfo() {
    const { ctx, app } = this
    try {
      const { phoneNumber, veriCode } = this.ctx.body
      const userData = await app.mysql.get('users', { phone: phoneNumber })
      if (userData?.user_id) {
        this.ctx.body = {
          code: 0,
          msg: '获取用户信息成功',
          data: userData,
        }
      } else {
        this.ctx.body = {
          code: -1,
          msg: '手机号错误，请重试',
        }
      }
    } catch (error) {
      this.ctx.body = {
        code: -1,
        data: error.message,
      }
    }
  }

  async getUserInfoCostom() {
    const { ctx, app } = this

    ctx.body = {
      code: 0,
      data: ctx.state.user
    }
  }

  // 模版库接口 templates
  async templateList() {
    const { ctx, app } = this
    const { pageIndex, pageSize } = ctx.query
    console.log('pageIndex, pageSize:', pageIndex, pageSize)
    const res = await this.app.mysql.select('templates', {
      orders: [['id', 'desc']], // 排序方式
      limit: parseInt(pageSize), // 返回数据量
      offset: pageIndex * pageSize, // 数据偏移量
    })
    const total = await this.app.mysql.query(
      'SELECT COUNT(*) AS total_count FROM templates;'
    )
    ctx.helper.success({ ctx, res: { total: total[0].total_count, list: res } })
  }
  // 模版库接口 templates
  async template() {
    const { ctx, app } = this
    const { id } = ctx.params
    const res = await this.app.mysql.select('templates', {
      // 搜索 post 表
      where: { id }, // WHERE 条件
      orders: [['id', 'desc']], // 排序方式
    })
    ctx.helper.success({ ctx, res })
  }

  // users/genVeriCode
  async genVeriCode() {
    const { ctx, app } = this
    let result = captcha.create()
    // 将result.text 存入session对象，返回客户端一个sid
    ctx.session.answer = result.text
    ctx.type = 'svg'
    ctx.body = { code: 0, data: result.text }
  }
}

module.exports = userController
